import { CreepAbilityHelper } from "utils/creep/CreepAbilityHelper";
import { ActionBase } from "../../ActionBase";
import { EActionCode } from "framework/FSM/Action/ActionCode";

/**
 * 放置site Action
 */
export class ActionTowerDefend  extends ActionBase<IActionCMD<"towerDefend">>
{
    public execute(action: IActionCMD<"towerDefend">): ActionCode 
    {
       
        const room = action.arg.entity as Required<Room>;
        if(!room)
        {
            return 0;
        }
     
        let enemy = room.memory.warinfo?.enemy;
        
        if(!enemy)
        {
            const cachehostiles = room.getWorld().PollHostiles(room.name);
            if(cachehostiles)
            {
                enemy = cachehostiles.cacheData.map(e=>e.id);
            }
            
        }
      
        if(!enemy)
        {
            return 0;
        }
      
        const enemycreeps =  _.sortBy(enemy.map(e=>Game.getObjectById(e)),f=>f?.getActiveBodyparts(HEAL)) as Creep[];
        const cache = room.getWorld().PollStructure(room.name);
        if(cache)
        {
            const max_heal = _.sum( enemycreeps.filter(e=>e.pos.isNearTo(enemycreeps[0])&& e.getActiveBodyparts(HEAL)),c=>CreepAbilityHelper.getCreepHealAbility(c));
            if(cache.inquireDamage(enemycreeps[0].pos)<=max_heal)
            {
                room.log('warn',JSON.stringify(enemycreeps[0].pos),`无法击穿敌方单位`,`伤害:${cache.inquireDamage(enemycreeps[0].pos)}`,`恢复:${max_heal}`);
                return EActionCode.RUNNING;
            }
        }
        
        if(Game.time%5 == 0)
        {
            room.harass(enemycreeps);
        }
        else
        {
            room.focuseFire(enemycreeps);
        }
   
        return 0;
    }
}